<template>
  <div class="send-display-container">
    <div class="filter-container">
      <div class="label">角色名称：</div>
      <div class="input-container">
        <a-input v-model="queryFrom.roleName"/>
      </div>
      <a-button type="primary" class="btn" @click="initList">查询</a-button>
      <a-button class="btn" @click="resetForm">重置</a-button>
    </div>
    <div class="filter-container">
      <a-button type="primary" class="btn" @click="showModal">新建</a-button>
      <a-modal
        width="50%"
        :title="title"
        :visible="addVisible"
        :confirm-loading="confirmLoading"
        @ok="handleOk"
        @cancel="handleCancel"
      >
        <div style="margin-top: 24px">

          <a-form-model
            ref="ruleAddForm"
            :model="addForm"
            :rules="addRules"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
          >
            <a-row>
              <a-col :span="24">
                <a-form-model-item ref="roleName" label="角色名称" prop="roleName">
                  <a-input
                    v-model="addForm.roleName"
                    @blur="() => { $refs.roleName.onFieldBlur() }"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item ref="roleCode" label="角色编码" prop="roleCode">
                  <a-input
                    v-model="addForm.roleCode"
                    @blur="() => { $refs.roleCode.onFieldBlur() }"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item ref="bz" label="备注" prop="bz">
                  <a-input :rows="4" v-model="addForm.bz" type="textarea"></a-input>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </div>
      </a-modal>
    </div>
    <div>
      <a-table
        :loading="loading"
        :columns="columns"
        :data-source="data"
        bordered
        :pagination="pagination"
        :rowKey="(record,index)=>{return index}">
        <a slot="b" slot-scope="text" href="https://www.google.com">{{ text }}</a>
        <span slot="action" slot-scope="text, record">
          <a href="javascript:" @click="updateShowModal( text, record.roleId )">编辑</a>
          <a-divider type="vertical"/>
          <a-dropdown>
            <a class="ant-dropdown-link">
              更多 <a-icon type="down"/>
            </a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a href="javascript:" @click="onAuthorization( text, record.roleId, record.roleCode )">授权</a>
                <a-drawer
                  title="角色授权"
                  width="30%"
                  :visible="visible"
                  :body-style="{ paddingBottom: '80px' }"
                  @close="onClose"
                >
                  <a-tree
                    v-model="menuIds"
                    checkable
                    :checkStrictly="checkStrictly"
                    :selectedKeys="selectedKeys"
                    :expandedKeys="expandedKeysss"
                    :checkedKeys="checkedKeys"
                    :defaultExpandAll="defaultExpandAll"
                    :replace-fields="replaceFields"
                    :tree-data="treeData"
                    @select="onSelect"
                    @check="onAuthorizationSet"
                    @expand="onExpand"
                  />
                  <div
                    :style="{
                      position: 'absolute',
                      right: 0,
                      bottom: 0,
                      width: '100%',
                      borderTop: '1px solid #e9e9e9',
                      padding: '10px 16px',
                      background: '#fff',
                      textAlign: 'right',
                      zIndex: 1,
                    }"
                  >
                    <a-dropdown style="float: left" :trigger="['click']" placement="topCenter">
                      <a-menu slot="overlay">
                        <a-menu-item key="1" @click="switchCheckStrictly(1)">父子关联</a-menu-item>
                        <a-menu-item key="2" @click="switchCheckStrictly(2)">取消关联</a-menu-item>
                        <a-menu-item key="3" @click="checkALL">全部勾选</a-menu-item>
                        <a-menu-item key="4" @click="cancelCheckALL">取消全选</a-menu-item>
                        <a-menu-item key="5" @click="expandAll">展开所有</a-menu-item>
                        <a-menu-item key="6" @click="closeAll">合并所有</a-menu-item>
                      </a-menu>
                      <a-button>
                        树操作 <a-icon type="up" />
                      </a-button>
                    </a-dropdown>
                    <a-button :style="{ marginRight: '8px' }" @click="onClose">
                      取消
                    </a-button>
                    <a-button type="primary" @click="onAuthorizationUpdate">
                      保存
                    </a-button>
                  </div>
                </a-drawer>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm
                  title="是否删除？"
                  ok-text="是"
                  cancel-text="否"
                  @confirm="confirmDel( text, record.roleId )"
                  @cancel="cancelDel"
                >
                  <a href="#">删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </a-table>
    </div>
    <a-back-top />

  </div>
</template>

<script>
  import { getRoleList, addRoleInfo, deleteRoleInfo, getRoleInfo, updateRoleInfo, getResourceList, getResourceListByRoleId } from '@/api/rbac'
  import { TreeSelect } from 'ant-design-vue'
  const SHOW_PARENT = TreeSelect.SHOW_PARENT

  const columns = [
    {
      title: '角色编码',
      dataIndex: 'roleCode',
      key: 'roleCode',
      align: 'center'
    },
    {
      title: '角色名称',
      dataIndex: 'roleName',
      key: 'roleName',
      align: 'center'
    },
    {
      title: '备注',
      dataIndex: 'bz',
      key: 'bz',
      align: 'center'
    },
    {
      title: '操作',
      dataIndex: 'action',
      align: 'center',
      scopedSlots: { customRender: 'action' }
    }

  ]

  export default {
    name: 'Role',
    data () {
      return {
        SHOW_PARENT,
        data: [],
        columns,
        addForm: {
          roleId: '',
          roleName: '',
          roleCode: '',
          bz: ''
        },
        replaceFields: {
          children: 'children',
          title: 'menuName',
          value: 'menuId',
          key: 'menuId'
        },
        addRules: {
          roleName: [
            { required: true, message: '请输入角色名称!', trigger: 'blur' }
          ],
          roleCode: [
            { required: true, message: '请输入角色编码!', trigger: 'blur' }
          ]
        },
        autoExpandParent: true,
        selectedKeys: [],
        expandedKeysss: [],
        allTreeKeys: [],
        defaultExpandAll: true,
        loading: false,
        visible: false,
        addVisible: false,
        confirmLoading: false,
        wrapperCol: { span: 14 },
        labelCol: { span: 4 },
        title: '',
        queryFrom: {
          roleName: ''
        },
        pagination: {
          current: 1,
          pageSize: 10,
          total: 0,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `显示第${range[0]}至${range[1]}项结果，共${total}项`
        },
        treeData: [],
        menuIds: [],
        checkStrictly: true,
        menuIdsString: '',
        checkedKeys: []
      }
    },
    mounted () {
      this.initList()
    },
    methods: {
      initList () {
        this.pagination.current = 1
        this.onQuery()
        this.onAuthorizationTree()
      },
      onAuthorizationTree () {
        getResourceList({}).then(res => {
          if (res.retCode === 0) {
            this.treeData = res.retObj
            const check = []
            res.retObj.forEach(x => {
              check.push(x.menuId)
              if (x.children !== null && x.children !== undefined && x.children.length > 0) {
                this.forEachChild(check, x.children)
              }
            })
            this.allTreeKeys = check
            this.expandedKeysss = check
          } else {
            this.$notification['error']({
              message: '提示',
              description: res.retMsg,
              duration: 8
            })
          }
        })
      },
      forEachChild (check, data) {
        data.forEach(x => {
          check.push(x.menuId)
          if (x.children !== null && x.children !== undefined && x.children.length > 0) {
            this.forEachChild(check, x.children)
          }
        })
      },
      onAuthorizationSet (checkedKeys) {
        if (this.checkStrictly) {
          this.menuIds = checkedKeys.checked
        } else {
          this.menuIds = checkedKeys
        }
        console.log(this.menuIds)
        if (this.menuIds.length > 0) {
          this.menuIdsString = this.menuIds.toLocaleString()
        }
      },
      onAuthorization (text, roleId, roleCode) {
        const that = this
        this.menuIds = []
        this.menuIdsString = ''
        this.visible = true
        this.addForm.roleId = roleId
        this.addForm.roleCode = roleCode
        getResourceListByRoleId({ 'roleId': roleId }).then(res => {
          res.retObj.forEach(x => {
            that.menuIds.push(x.menuId)
          })
        })
      },
      onExpand (expandedKeys) {
        this.expandedKeysss = expandedKeys
        this.autoExpandParent = false
      },
      onAuthorizationUpdate () {
        const params = {
          roleId: this.addForm.roleId,
          roleCode: this.addForm.roleCode,
          menuIds: this.menuIdsString
        }
        console.log('params', params)
        updateRoleInfo(params).then(res => {
          if (res.retCode === 0) {
            this.$notification['success']({
              message: '提示',
              description: '角色授权成功！',
              duration: 8
            })
            this.onQuery()
            this.visible = false
          } else {
            this.$notification['error']({
              message: '提示',
              description: res.retMsg,
              duration: 8
            })
          }
        })
      },
      onQuery () {
        this.loading = true
        const params = {
          roleName: this.queryFrom.roleName === '' ? null : this.queryFrom.roleName,
          currentPage: this.pagination.current.toString(),
          pageSize: this.pagination.pageSize.toString()
        }
        getRoleList(params).then(res => {
          this.loading = false
          if (res.retCode === 0) {
            this.data = res.retObj.data
            this.pagination.total = parseInt(res.retObj.count)
          }
        }).catch(error => {
          this.loading = false
          console.log(error)
        })
      },
      showModal () {
        this.addVisible = true
        this.title = '新增角色'
        this.flag = true
        this.addForm = {
          roleId: '',
          roleName: '',
          roleCode: '',
          bz: ''
        }
      },
      updateShowModal (text, roleId) {
        this.addVisible = true
        this.title = '编辑角色'
        this.flag = false
        getRoleInfo({ 'roleId': roleId }).then(res => {
          this.addForm = res.retObj
        })
      },
      confirmDel (text, roleId) {
        deleteRoleInfo({ 'roleId': roleId }).then(res => {
          if (res.retCode === 0) {
            this.$notification['success']({
              message: '提示',
              description: '删除成功！',
              duration: 8
            })
            this.onQuery()
          } else {
            this.$notification['error']({
              message: '提示',
              description: res.retMsg,
              duration: 8
            })
          }
        })
      },
      onSave () {
        this.$refs.ruleAddForm.validate(valid => {
          if (valid) {
            const params = {
              roleName: this.addForm.roleName,
              roleCode: this.addForm.roleCode,
              bz: this.addForm.bz
            }
            addRoleInfo(params).then(res => {
              if (res.retCode === 0) {
                this.$notification['success']({
                  message: '提示',
                  description: '角色信息保存成功！',
                  duration: 8
                })
                this.onQuery()
                this.addForm = {
                    roleId: '',
                    roleName: '',
                    roleCode: '',
                    bz: ''
                }
                this.addVisible = false
              } else {
                this.$notification['error']({
                  message: '提示',
                  description: res.retMsg,
                  duration: 8
                })
              }
            })
          } else {
            return false
          }
        })
      },
      onUpdate () {
        this.$refs.ruleAddForm.validate(valid => {
          if (valid) {
            const params = {
              roleId: this.addForm.roleId,
              roleName: this.addForm.roleName,
              roleCode: this.addForm.roleCode,
              bz: this.addForm.bz
            }
            updateRoleInfo(params).then(res => {
              if (res.retCode === 0) {
                this.$notification['success']({
                  message: '提示',
                  description: '角色信息修改成功！',
                  duration: 8
                })
                this.onQuery()
                this.addVisible = false
              } else {
                this.$notification['error']({
                  message: '提示',
                  description: res.retMsg,
                  duration: 8
                })
              }
            })
          } else {
            return false
          }
        })
      },
      switchCheckStrictly (v) {
        if (v === 1) {
          this.checkStrictly = false
        } else if (v === 2) {
          this.checkStrictly = true
        }
      },
      expandAll () {
        this.expandedKeysss = this.allTreeKeys
      },
      closeAll () {
        this.expandedKeysss = []
      },
      checkALL () {
        this.menuIds = this.allTreeKeys
      },
      cancelCheckALL () {
        // this.checkedKeys = this.defaultCheckedKeys
        this.menuIds = []
      },
      onSelect (selectedKeys, info) {
        console.log('selected', selectedKeys, info)
      },
      handleOk () {
        if (this.flag) {
          this.onSave()
        } else {
          this.onUpdate()
        }
      },
      handleCancel () {
        this.addVisible = false
        this.addForm = {
          roleId: '',
          roleName: '',
          roleCode: '',
          bz: ''
        }
      },
      cancelDel () {
      },
      onClose () {
        this.visible = false
      },
      resetForm () {
        this.queryFrom.roleName = ''
        this.initList()
      }
    }
  }
</script>

<style scoped lang="less">
  .send-display-container {
    width: 100%;
    background-color: #ffffff;
    padding: 24px;
  }

  .filter-container {
    display: flex;
    align-items: center;
    padding-bottom: 24px;
    justify-content: left;

    .label {
      padding-right: 20px;
      white-space: nowrap;
    }

    .input-container {
      width: 200px;
      margin-right: 20px
    }

    .btn {
      margin-right: 20px;
    }
  }
</style>
